package co.za.itweb.itweblite;

import java.net.URL;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class Refresh extends Activity {
	RefreshTask rt;
	List<String> feedList = new Vector<String>(0);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		if (internetConnection()) {

			rt = new RefreshTask(this);
			
			if (rt.getStatus() == AsyncTask.Status.PENDING) {
				// My AsyncTask has not started yet
				rt.execute();
			}

			if (rt.getStatus() == AsyncTask.Status.RUNNING) {
				// My AsyncTask is currently doing work in doInBackground()
			}

			if (rt.getStatus() == AsyncTask.Status.FINISHED) {
				// My AsyncTask is done and onPostExecute was called
				
			}

		} else {
			Toast.makeText(getApplicationContext(),
					"No Internet connection ...", Toast.LENGTH_LONG).show();
			Refresh.this.finish();
		}

	}

	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	@Override
	public void onPause() {
		super.onPause();
		if (rt.getStatus() == AsyncTask.Status.RUNNING ) {
			rt.dialog.dismiss();
			rt.cancel(true);
			

		}

	}

	

	private class RefreshTask extends AsyncTask<Void, Integer, Void> {
		 Vector<RSSFeed> fList2 = new Vector<RSSFeed>(0);
		RSSFeed feed;
		ProgressDialog dialog;
		

		public RefreshTask(Refresh activity) {
			
			dialog = new ProgressDialog(activity);
			dialog.setMessage("Refreshing...");
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setCancelable(true);
			dialog.setMax(100);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
		          public void onCancel(DialogInterface dialog) {
		              rt.cancel(true);
		              Intent returnIntent = new Intent();
		  			setResult(RESULT_CANCELED, returnIntent);
		              Refresh.this.finish();
		          }
		    });
		}

		protected void onPreExecute() {
			
			
			
			this.dialog.show();
			
		}

		@Override
		protected Void doInBackground(Void... params) {

			for (int o = 0; o < FirstScreen.feeds.length; o++) {
				if (isCancelled()){
				    break;
				}else{
				feed = getFeed(FirstScreen.feeds[o]);
				
				if (feed != null) {
					fList2.add(feed);
					System.out
							.println("-----------------------------------------------"
									+ FirstScreen.feeds[o].toString());
					int x = o * (100 / FirstScreen.feeds.length);
					publishProgress(x);
					

				}

			}
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			dialog.setProgress(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing()) {
				dialog.dismiss();
				FirstScreen.fList.clear();
				FirstScreen.fList=fList2;
				Intent returnIntent = new Intent();
				setResult(RESULT_OK, returnIntent);
				finish();
			}
			

		}
	}

	public boolean addFeedsToList(String feedstring) {
		try {
			if (feedList.add(feedstring)) {
				return true;
			}

		} catch (Exception ex) {

			return false;
		}
		return false;

	}
	

	public RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"
					+ theRssHandler.getFeed());
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
					+ ee.toString());
			return null;
		}
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
	    if ((keyCode == KeyEvent.KEYCODE_BACK))
	    {
	    	System.out.println("BBBBBBBBBBBAAAAAAAAAAAAACCCCCCCCCCCCCCKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
	    	if(rt.dialog.isShowing()){
	    	rt.dialog.dismiss();
	    	rt.cancel(true);
	    	
	    	Intent returnIntent = new Intent();
			setResult(RESULT_CANCELED, returnIntent);
			Refresh.this.finish();
	    	}
	    	
	    	 return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	

}